package cn.nawang.ebeim.api.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.nawang.ebeim.api.bean.UpdatePassword;
import cn.nawang.ebeim.api.comm.BaseController;
import cn.nawang.ebeim.api.domain.ShortMessage;
import cn.nawang.ebeim.api.domain.User;
import cn.nawang.ebeim.api.service.UserService;
import cn.nawang.ebeim.api.utils.Constant;
import cn.nawang.ebeim.api.utils.JsonUtil;
import cn.nawang.ebeim.api.utils.Util;
import cn.nawang.ebeim.api.utils.ValidateUtil;
import cn.nawang.ebeim.verification.SmsVerification;

/**
 * @ClassName: ShortMessageController
 * @Description: TODO
 * @author fanyb
 * @date Oct 26, 2015 5:46:17 PM
 * @version v1.0
 */
@RestController
public class ShortMessageController extends BaseController {
  private static final Logger LOG = LoggerFactory.getLogger(ShortMessageController.class);

  @Autowired
  private UserService userService;

  /**
   * 
   * @author fanyb
   * @Description: 获取根据用户名称获取验证码
   * @param username
   * @return Map<String,Object>
   * @date Oct 26, 20155:51:24 PM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/token/short_message/send", method = RequestMethod.GET)
  public Map<String, Object> getShortMessage(String username) {
    LOG.debug("/token/short_message/send {}", username);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("code", Constant.CODE_ERROR);
    User user = userService.findUserByUsername(username);
    if (!validSend(map, user)) {
      return map;
    }
    map.put("desc", "发送成功！请查收短信。");
    map.put("code", Constant.CODE_SUCCESS);
    LOG.debug("getShortMessage", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 短信验证码验证结果
   * @param username
   * @param code
   * @return Map<String,Object>
   * @date Oct 26, 20155:53:34 PM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/token/short_message/check", method = RequestMethod.GET)
  public Map<String, Object> checkShortMessage(String username, String code) {
    LOG.debug("/token/short_message/check {}", username, code);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("code", Constant.CODE_ERROR);
    User user = userService.findUserByUsername(username);
    if (!validCheck(map, user, code)) {
      return map;
    }
    map.put("desc", "短信验证通过。");
    map.put("code", Constant.CODE_SUCCESS);
    LOG.debug("checkShortMessage {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 返回结果解析成对象
   * @param result
   * @return ShortMessage
   * @date Oct 26, 20157:15:32 PM
   *
   * @修改人
   * @修改日期
   */
  public ShortMessage parseShortMessage(String result) {
    return (ShortMessage) JsonUtil.toObject(result, ShortMessage.class);
  }

  /*
   * 短信发送效验接口
   */
  public boolean validSend(Map<String, Object> resultMap, User user) {
    if (ValidateUtil.isNull(user)) {
      resultMap.put("desc", "用户不存在。");
      return false;
    }
    SmsVerification sv = new SmsVerification();
    String result = sv.verify(user.getMobile());
    ShortMessage shortMessage = parseShortMessage(result);
    if (!Constant.SHORT_MESSAGE_CODE_000000.equals(shortMessage.getCode())) {
      resultMap.put("desc", Constant.SHORT_MESSAGE_CODE.get(shortMessage.getCode()));
      return false;
    }
    return true;
  }

  /*
   * 短信效验验证接口
   */
  public boolean validCheck(Map<String, Object> resultMap, User user, String code) {
    if (ValidateUtil.isNull(user)) {
      resultMap.put("desc", "用户不存在。");
      return false;
    }
    if (Util.isBlank(code)) {
      resultMap.put("desc", "请输入验证码。");
      return false;
    }
    if (code.length() != 6) {
      resultMap.put("desc", "验证码输入位数有误，请输入6位验证码");
      return false;
    }
    // 验证验证码是否成功
    SmsVerification sv = new SmsVerification();
    String result = sv.verifyCode(user.getMobile(), code);
    ShortMessage shortMessage = parseShortMessage(result);
    if (!Constant.SHORT_MESSAGE_CODE_000001.equals(shortMessage.getCode())) {
      resultMap.put("desc", Constant.SHORT_MESSAGE_CODE.get(shortMessage.getCode()));
      return false;
    }
    return true;
  }

  /**
   * 
   * @author fanyb
   * @Description: 修改密码（需要短信验证码的接口）
   * @param userId
   * @param oldPassword
   * @param newPassword
   * @param request
   * @param code
   * @return Map<String,Object>
   * @date Oct 28, 20158:36:42 AM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/token/short_message/update_password", method = RequestMethod.POST)
  public Map<String, Object> updatePasswordShortMessageCheck(String userId, String oldPassword,
      String newPassword, HttpServletRequest request, String code, String type) {
    LOG.debug("/token/short_message/update_password {}", userId, oldPassword, newPassword, code, type);
    Map<String, Object> resultMap = new HashMap<String, Object>();
    User user = userService.findOne(userId);
    boolean valid =
        this.validUpdatePassword(resultMap, code, userId, oldPassword, newPassword, user, type);
    if (!valid) {
      return resultMap;
    }
    user.setPassword(Util.hash(newPassword));
    user.setIsUpdateDefaultPwd(Constant.YES);
    user.setLmTime(new Date().getTime());
    user.setLmUserId(user.getId());
    user.setUpdatePassTime(new Date().getTime());
    boolean flag = userService.update(user);
    if (flag) {
      resultMap.put("code", Constant.CODE_SUCCESS);
      request.getSession().removeAttribute("user");
      resultMap.put("desc", "密码修改成功，请重新登录。");
    } else {
      resultMap.put("code", Constant.CODE_ERROR);
      resultMap.put("desc", "服务器忙，请稍后再试。");
    }
    LOG.debug("updatePasswordShortMessageCheck {}", resultMap);
    return resultMap;
  }

  @RequestMapping(value = "/token/web_ui/short_message/update_password", method = RequestMethod.POST)
  public Map<String, Object> updatePasswordShortMessageCheck(
      @RequestBody UpdatePassword updatePassword) {
    LOG.debug("/token/web_ui/short_message/update_password {}", updatePassword);
    Map<String, Object> resultMap = new HashMap<String, Object>();
    String userId = updatePassword.getUserId();
    String code = updatePassword.getCode();
    String oldPassword = updatePassword.getOldPassword();
    String newPassword = updatePassword.getNewPassword();
    String type = updatePassword.getType();
    User user = userService.findOne(userId);
    boolean valid =
        this.validUpdatePassword(resultMap, code, userId, oldPassword, newPassword, user, type);
    if (!valid) {
      return resultMap;
    }
    user.setPassword(Util.hash(newPassword));
    user.setIsUpdateDefaultPwd(Constant.YES);
    user.setLmTime(new Date().getTime());
    user.setLmUserId(user.getId());
    user.setUpdatePassTime(new Date().getTime());
    boolean flag = userService.update(user);
    if (flag) {
      resultMap.put("code", Constant.CODE_SUCCESS);
      resultMap.put("desc", "密码修改成功，请重新登录。");
    } else {
      resultMap.put("code", Constant.CODE_ERROR);
      resultMap.put("desc", "服务器忙，请稍后再试。");
    }
    LOG.debug("updatePasswordShortMessageCheck {}", updatePassword);
    return resultMap;
  }

  /**
   * 
   * @author fanyb
   * @Description: 需改密码验证
   * @param resultMap
   * @param code
   * @param userId
   * @param oldPassword
   * @param newPassword
   * @param user
   * @param type 0：有旧密码的修改；1：忘记密码修改
   * @return boolean
   * @date Nov 5, 20158:52:21 AM
   *
   * @修改人
   * @修改日期
   */
  public boolean validUpdatePassword(Map<String, Object> resultMap, String code, String userId,
      String oldPassword, String newPassword, User user, String type) {
    if (Util.isBlank(userId)) {
      resultMap.put("code", Constant.CODE_ERROR);
      resultMap.put("desc", "参数有误。");
      return false;
    }
    if ("0".equals(type) && Util.isBlank(oldPassword)) {
      resultMap.put("code", Constant.CODE_ERROR);
      resultMap.put("desc", "请输入旧密码。");
      return false;
    }
    if ("0".equals(type) && !user.getPassword().toUpperCase().equals(Util.hash(oldPassword))) {
      resultMap.put("code", Constant.CODE_ERROR);
      resultMap.put("desc", "很抱歉，您输入的旧密码有误。");
      return false;
    }
    if (Util.isBlank(newPassword)) {
      resultMap.put("code", Constant.CODE_ERROR);
      resultMap.put("desc", "请输入新密码。");
      return false;
    }
    if (user == null) {
      resultMap.put("code", Constant.CODE_ERROR);
      resultMap.put("desc", "很抱歉，您要修改的用户不存在。");
      return false;
    }
    if(oldPassword!=null && oldPassword.equals(newPassword)){
      resultMap.put("code", Constant.CODE_ERROR);
      resultMap.put("desc", "新密码与旧密码不能相同。");
      return false;
    }
    if (!Util.pwdFormat(newPassword)) {
      resultMap.put("desc", "至少六位的英文数字组合。");
      return false;
    }
    if (Util.isBlank(code)) {
      resultMap.put("desc", "请输入验证码。");
      return false;
    }
    if (code.length() != 6) {
      resultMap.put("desc", "验证码输入位数有误，请输入6位验证码");
      return false;
    }
    // 验证验证码是否成功
    SmsVerification sv = new SmsVerification();
    String result = sv.verifyCode(user.getMobile(), code);
    ShortMessage shortMessage = parseShortMessage(result);
    if (!Constant.SHORT_MESSAGE_CODE_000001.equals(shortMessage.getCode())) {
      resultMap.put("desc", Constant.SHORT_MESSAGE_CODE.get(shortMessage.getCode()));
      return false;
    }
    return true;
  }
}
